﻿package com.project.action;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONArray;
import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionContext;
import com.project.entity.*;
import com.project.service.*;
public class InputAction {
	private Announcement announcement;
	private News			news;
	private com.project.service.AnnouncementManager	announcementManager;
	private com.project.service.NewsManage			newsManage;
	
	private String start,limit;
	private String inqueryType,inqueryText;
	private String pageMessage;
	private File upload;		//上传的文件，在extjs 中对应 xtype:'fileuploadfield',  name:'upload'
	private String uploadFileName;	//上传的文件名
	private String uploadContentType; //限制上传的后缀名
	private String savePath;
	private String caption;		//form中其他的上传的字段
	private Boolean success = true;	//json中返回的结果
	private String resultMsg = "ok" ;  //上传失败后，返回的错误结果
	

	private String jsonString;
	
	
	void clearValue(){
		this.start = null;
		this.limit = null;
		this.inqueryText = null;
		this.inqueryType = null;
		this.pageMessage = null;
	}
	/**********setter  and getter*****************/
	
	public Announcement getAnnouncement() {
		return announcement;
	}
	public File getUpload() {
		return upload;
	}
	public void setUpload(File upload) {
		this.upload = upload;
	}
	
	public String getUploadFileName() {
		return uploadFileName;
	}
	public void setUploadFileName(String uploadFileName) {
		this.uploadFileName = uploadFileName;
	}
	public String getUploadContentType() {
		return uploadContentType;
	}
	public void setUploadContentType(String uploadContentType) {
		this.uploadContentType = uploadContentType;
	}
	public String getPageMessage() {
		return pageMessage;
	}
	public void setPageMessage(String pageMessage) {
		this.pageMessage = pageMessage;
	}
	public String getInqueryType() {
		return inqueryType;
	}
	public void setInqueryType(String inqueryType) {
		this.inqueryType = inqueryType;
	}
	public String getInqueryText() {
		return inqueryText;
	}
	public void setInqueryText(String inqueryText) {
		this.inqueryText = inqueryText;
	}
	
	public String getSavePath() {
		return savePath;
	}
	public void setSavePath(String savePath) {
		this.savePath = savePath;
	}
	public String getCaption() {
		return caption;
	}
	public void setCaption(String caption) {
		this.caption = caption;
	}
	public Boolean getSuccess() {
		return success;
	}
	public void setSuccess(Boolean success) {
		this.success = success;
	}
	public String getResultMsg() {
		return resultMsg;
	}
	public void setResultMsg(String resultMsg) {
		this.resultMsg = resultMsg;
	}
	public void setAnnouncement(Announcement announcement) {
		this.announcement = announcement;
	}
	public News getNews() {
		return news;
	}
	public void setNews(News news) {
		this.news = news;
	}
	public String getStart() {
		return start;
	}
	public void setStart(String start) {
		this.start = start;
	}
	public String getLimit() {
		return limit;
	}
	public void setLimit(String limit) {
		this.limit = limit;
	}
	public String getJsonString() {
		return jsonString;
	}
	public void setJsonString(String jsonString) {
		this.jsonString = jsonString;
	}
	public com.project.service.AnnouncementManager getAnnouncementManager() {
		return announcementManager;
	}
	public void setAnnouncementManager(
			com.project.service.AnnouncementManager announcementManager) {
		this.announcementManager = announcementManager;
	}
	public com.project.service.NewsManage getNewsManage() {
		return newsManage;
	}
	public void setNewsManage(com.project.service.NewsManage newsManage) {
		this.newsManage = newsManage;
	}
	
	/***
	 * 新闻录入
	 * @return
	 * @throws IOException 
	 */

	public String insertnews() throws IOException{
		if(news != null){
			
			this.imageUpload();
			news.setCreatedtime(new Date());
			this.newsManage.insertNews(news);
			this.setJsonString("{success:true,totolCount:"+1+", list:"+1+"}");
		}else
			this.setJsonString("{success:true,totolCount:"+0+", list:"+0+"}");
		news = null;
		return "success";
	}
	
	
	/***
	 * 根据查询条件（可以不加任何查询条件） 以及分页来查找
	 * @return
	 */
	public String getAllNews(){
		Map<String,String> map = new HashMap<String,String>();
		map.put("start", start);
		map.put("limit", limit);
		if(this.inqueryType != null && !inqueryType.equals("") && inqueryText != null )
			map.put(inqueryType, inqueryText);
		List<News> newslist = this.newsManage.getAllNews(map);
		JSONArray jsonObject = JSONArray.fromObject(newslist);
		this.setJsonString("{success:true,totalCount : " + this.newsManage.totalCount(map)
				+ ", list:" + jsonObject.toString() + "}");
		clearValue();
		return "success";
	}
	
	/**
	 * 根据Id删除新闻
	 * @return
	 */
	public String deleteNewsById(){
		if( this.pageMessage == null || !pageMessage.equals(""))
			this.setJsonString("{success:false,mark:-1}");
		try{
			this.newsManage.deleteById(Integer.valueOf(pageMessage));
			this.setJsonString("{success:true,mark:1}");
		}catch (Exception e){
			e.printStackTrace();
			this.setJsonString("{success:false,mark:-2}");
		}
		return "success";
	}
	
	public String updateNews(){
		if(news == null  || news.getNewsid().equals("")){
			this.setJsonString("{success:false,mark:-1}");
			return "success";
		}
		news.setModifiedtime(new Date());
		news.setCreatedtime(null);
		try{
			this.newsManage.updateNews(news);
			this.setJsonString("{success:true,mark:1}");
		}catch(Exception e){
			this.setJsonString("{success:false,mark:-2}");
		}
		return "success";
	}
	/***
	 * 通知录入
	 */

	public String insertnotice() throws IOException{
		if(this.announcement != null){
			this.imageUpload();
			this.announcement.setCreatedtime(new Date());
			this.announcementManager.insertAnnouncement(announcement);
			this.setJsonString("{success:true,mark:"+1+", list:" + 1 + "}");
		}else
			this.setJsonString("{success:false,mark:"+0+"}");
		this.announcement = null; //清空变量
		return "success";
	}
	
	/**
	 * 根据查询条件（可以不加查询条件）以及分页来查询所有的通知
	 * @return
	 */
	public String	getAllnotice(){
		Map<String,String> map = new HashMap<String,String>();
		map.put("start", start);
		map.put("limit", limit);
		if(this.inqueryType != null && !inqueryType.equals("") && inqueryText != null )
			map.put(inqueryType, inqueryText);
		List<Announcement> announcelist = this.announcementManager.getAllNotice(map);
		JSONArray jsonObject = JSONArray.fromObject(announcelist);
		this.setJsonString("{success:true,totalCount : " + this.announcementManager.totalCount(map)
				+ ", list:" + jsonObject.toString() + "}");
		clearValue();
		return "success";
	}
	/**
	 * 根据ID删除通知
	 * @return
	 */
	public String deleteNoticeById(){
		if( this.pageMessage == null || !pageMessage.equals(""))
			this.setJsonString("{success:false,mark:-1}");
		try{
			this.announcementManager.deleteById(Integer.valueOf(pageMessage));
			this.setJsonString("{success:true,mark:1}");
		}catch (Exception e){
			e.printStackTrace();
			this.setJsonString("{success:false,mark:-2}");
		}
		this.clearValue();
		return "success";
	}
	
	/**
	 * 更新通知的内容
	 * @return
	 */
	public String updateNotice(){
		if(this.announcement == null  || this.announcement.getAnnouncementid().equals("")){
			this.setJsonString("{success:false,mark:-1}");
			return "success";
		}
		announcement.setModifiedtime(new Date());
		announcement.setCreatedtime(null);
		try{
			this.announcementManager.updateAnnouncement(announcement);
			this.setJsonString("{success:true,mark:1}");
		}catch(Exception e){
			this.setJsonString("{success:false,mark:-2}");
		}
		return "success";
	}
	

	private void imageUpload() throws IOException{
		HttpServletRequest request = ServletActionContext.getRequest(); 
		ActionContext context = ActionContext.getContext();
		Map session = context.getSession();
		if(session.get("login")==null){
			 resultMsg = "为登录，不能上传。请先登录！ ";
			 System.out.println(resultMsg);
			 success = false;
			 //return SUCCESS;
		 }
		String bathpath = request.getSession().getServletContext().getRealPath("/");
		if(session.get("right").equals("super")||session.get("right").equals("manager"))
			this.setSavePath(bathpath+"uploadFiles\\admin");
		else if(session.get("right").equals("user")){
			this.setSavePath(bathpath+"\\user");
			File userF = new File(this.getSavePath()+"\\"+session.get("number"));
			if(!(userF.exists())){
				userF.createNewFile();
				this.setSavePath(this.getSavePath()+"\\"+session.get("number"));
			}
		}
		//上面根据权限来判断上传文件的保存地址
		
		
	 try { //此处为最简单的文件拷贝方法
		java.io.FileInputStream is = new FileInputStream(upload);
		//this.setFileName(upload.getName());
		java.io.FileOutputStream os = new FileOutputStream(this.savePath+"\\"+uploadFileName);
		System.out.println("这里是在创建完成输出流以后！！！！！！！！");
		byte buffer[] = new byte[8192];
		int count = 0;
		while ((count = is.read(buffer)) > 0)
			os.write(buffer, 0, count);
		news.setNewimage(uploadFileName);
		announcement.setAnnouncementattachment(uploadFileName);
		os.close();
		is.close();
	 } catch (Exception e)
	 {
		 resultMsg = "上传文件失败，文件太大或没有选择上传的文件 ";
		 System.out.println(resultMsg);
		 success = false;
	 }
	 //此处会根据 success 和 resultMsg 返回 json
	 //{"resultMsg":"ok","success":true}
	//return SUCCESS;
	}
}
